06. Edge Case: Thread Execution Order

Edge Case: Thread Execution Order

In this lesson, you'll learn about the order in which parallel threads execute.

ND079 JPND C2 L05 A05 Edge Case Thread Execution Order

Thread Execution Order

You probably noticed in the exercise that when you have a bunch of threads running at the same time, they execute in seemingly random order. That's because threads are run by the operating system's thread scheduler.

There are ways you can try to nudge the scheduler one way or another, but ultimately, your program cannot diectly control it. That's why, if multiple threads are running at the same time, they could run in any order.

What is a Race Condition?

A race condition is a kind of software bug that happens when the correctness of a program depends on a particular execution order of parallel threads.

You saw an example of a race condition in the video above.

What could this program print?

Thread a = new Thread(() -> System.out.print("a"));
Thread b = new Thread(() -> System.out.print("b"));
Thread c = new Thread(() -> System.out.print("c"));

a.run();
b.run();
a.join();
c.run();
c.join();
b.join();
SOLUTION:
  • `abc`

What could this program print?

Thread a = new Thread(() -> System.out.print("a"));
Thread b = new Thread(() -> System.out.print("b"));
Thread c = new Thread(() -> System.out.print("c"));

a.start();
b.start();
a.join();
c.start();
c.join();
b.join();
SOLUTION:
  • `abc`
  • `acb`
  • `bac`